package com.campus.client.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.campus.pojos.domain.ChatList;
import com.campus.pojos.domain.ChatMessage;
import com.campus.pojos.domain.vo.ChatListVo;
import com.campus.result.Result;
import com.campus.service.ChatListService;
import com.campus.service.ChatMessageService;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.LocalDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/client/chat")
@Slf4j
/**
 * 聊天相关接口
 */
public class ChatController {

    @Autowired
    ChatMessageService chatMessageService;

    @Autowired
    private ChatListService chatListService;
    /**
     * 获取聊天内容
     * @param fromUserId
     * @param toUserId
     * @return
     */
    @GetMapping("/message")
    public Result<List<ChatMessage>> getMessage(
            @RequestParam(value = "fromUserId", required = true) Integer fromUserId,
            @RequestParam(value = "toUserId", required = true) Integer toUserId)
    {
        List<ChatMessage> messages=chatMessageService.getMessage(fromUserId,toUserId);
        return Result.success(messages);
    }

    /**
     * 获取聊天列表
     * @param id
     * @return
     */
    @GetMapping("/list/{id}")
    public Result<List<ChatListVo>> getChatList(@PathVariable Long id){
        log.info("查询id{}",id);
        return chatListService.chatList(id);
    }

    /**
     * 建立私聊关系
     * @param loginUserId
     * @param articleUserId
     * @return
     */
    @PostMapping("/add")
    public Result addChat(
            @RequestParam(value = "loginUserId", required = true) Long loginUserId,
            @RequestParam(value = "articleUserId", required = true) Long articleUserId
    ){
        log.info("私聊关系{}，{}",loginUserId,articleUserId);
        if(Objects.equals(loginUserId, articleUserId)) return Result.error("不能与自己私聊");

        chatListService.save(new ChatList(null,loginUserId,articleUserId,0));
        chatListService.save(new ChatList(null,articleUserId,loginUserId,0));
        return Result.success();
    }

    /**
     * 已读消息
     * @param loginUserId
     * @param toUserId
     * @return
     */
    @PutMapping("/read")
    public Result read(
            @RequestParam(value = "loginUserId", required = true) Long loginUserId,
            @RequestParam(value = "toUserId", required = true) Long toUserId
    ){

        chatListService.read(loginUserId, toUserId);
        return Result.success();
    }
}
